package dtd.PHS.VND_ExchangeRate.widget;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import dtd.PHS.VND_ExchangeRate.data.VNExDatabase;
import dtd.PHS.VND_ExchangeRate.utils.ApplicationContext;
import dtd.PHS.VND_ExchangeRate.utils.Helpers;
import dtd.PHS.VND_ExchangeRate.utils.Logger;
import dtd.PHS.VND_ExchangeRate.utils.PreferencesHelpers;

public class RateWidgetProvider extends AppWidgetProvider {

//	private static final long UPDATE_WIDGET_PERIOD = 120*60*1000; //2 hours

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		
		ApplicationContext.setContext(context);
		if ( Helpers.isFirstTimeRunning() ) {
			try {
				VNExDatabase.createDBFromStatic();
				VNExDatabase.setCreatedTimeDB(0);
				Helpers.setPreference(Helpers.PREF_FIRST_TIME_RUNNING,"false");
			} catch (Exception e) {
				Logger.logError("Init global data: Exception: " + e.getClass().toString() + " :: "  + e.getMessage());
			}
		}
		
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		PendingIntent pendingService = getServicePendingIntent(context);
		am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), PreferencesHelpers.getWidgetUpdatePeriod(), pendingService);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		Helpers.initGlobalData(context);
		super.onReceive(context, intent);
	}
	
	private PendingIntent getServicePendingIntent(Context context) {
		PendingIntent pendingService = PendingIntent.getService(context, 0, new Intent(context,UpdateWidgetService.class), PendingIntent.FLAG_UPDATE_CURRENT);
		return pendingService;
	}
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		// TODO Auto-generated method stub
		super.onUpdate(context, appWidgetManager, appWidgetIds);
	    Intent i = new Intent(context,UpdateWidgetService.class);
	    context.startService(i);
	}
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);
		VNExDatabase.deleteWidgets( appWidgetIds );
	}
	
	@Override
	public void onDisabled(Context context) {	
		super.onDisabled(context);
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		am.cancel(getServicePendingIntent(context));
	}

}
